package com.woniu.ai;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.*;

public class AiKeep {
    // 将messages定义为类属性，用于保存多轮对话的历史信息
    private List<Map<String, String>> messages = new ArrayList<>();

    public String generate(String content) throws Exception {

        // 构造用户提问的一条Map对象，格式为：{"role": "user","content": "用户的问题内容"}
        Map<String, String> message_user = new HashMap<>();
        message_user.put("role", "user");
        message_user.put("content", content);
        messages.add(message_user);

        String url = "http://127.0.0.1:11434/api/chat";
        // 注意：多轮对话的参数是messages而不是prompt，且参数类型不再是一个字符串，而是一个JSON数组
        String json = "{'model': 'deepseek-r1:1.5b','messages': %s, 'stream':false}"
                .formatted(JSONObject.toJSONString(messages))
                .replace("'", "\"");
        String response = WoniuAi.doPost(url, json);

        // 解析JSON字符串
        try {
            Map<String, Map<String, String>> map = JSONObject.parseObject(response, Map.class);
            String output = map.get("message").get("content");

            // 构造AI回答的Map对象，格式为：{"role":"assistent","content":"AI的回答内容"}
            Map<String, String> message_ai = new HashMap<>();
            message_ai.put("role", "assistent");
            message_ai.put("content", output);
            messages.add(message_ai);

            // 输出消息历史看看
            System.out.println(JSONObject.toJSONString(messages));
            return output;
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
    public static void main(String[] args) throws Exception {
        AiKeep chat = new AiKeep();
        // 利用命令行输入进行多轮对话模拟
        Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.println("\n请输入你的问答：");
            String content = scanner.nextLine();
            String answer = chat.generate(content);
            System.out.println("本轮AI的回答为：");
            System.out.println(answer);
        }
    }

}
